﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace HooIzDat.Web.Models
{
    public class CharacterRepository : Repository, ICharacterRepository
    {
        public IQueryable<Character> FindAllCharacters()
        {
            return Db.Characters;
        }

        public IQueryable<int> FindAllCharacterIds()
        {
            return from c in Db.Characters
                   orderby Guid.NewGuid()
                   select c.CharacterID;
        }

        public IQueryable<CharacterTrait> FindAllCharacterTraits()
        {
            return Db.CharacterTraits;
        }

        public IEnumerable<string> FindAllQuestions()
        {
            return FindAllCharacterTraits()
                    .OrderBy(t => t.TraitVariationID)
                    .Select(t => t.Trait.QuestionFormat
                            .Replace("{variation}", t.TraitVariation != null ?
                                t.TraitVariation.Name : ""))
                    .Distinct();
        }

        public Character GetCharacter(int id)
        {
            return Db.Characters.SingleOrDefault(p => p.CharacterID == id);
        }

        public void Add(Character character)
        {
            Db.Characters.AddObject(character);
        }

        public void Delete(Character character)
        {
            Db.Characters.DeleteObject(character);
        }

        public void Save()
        {
            Db.SaveChanges();
        }
    }
}